package com.helloandroid.paso.ui.mediaplayer;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;

public class Playlist {
	
	private ArrayList<Track> playlist;
	private int currTrack;
	private IPlaylistStatusListener listener;
	
	public void next(){
		if(currTrack >= playlist.size() - 1){
			currTrack = 0;
		}
		else{
			currTrack++;
		}
		
		trackChange(playlist.get(currTrack));
	}
	
	public ArrayList<Track> getPlaylist(){
		return playlist;
	}
	
	public void setCurrentTrack(Track track){
		currTrack = playlist.indexOf(track);
		trackChange(track);
	}
	
	public Track getCurrentTrack(){
		return playlist.get(currTrack);
	}
	
	public void setPlaylistStatusListener(IPlaylistStatusListener listener){
		this.listener = listener;
	}
	
	private void successfulLoad(){
		if(listener != null)
			listener.onSuccessfulPlaylistLoad();
	}
	
	private void failedLoad(){
		if(listener != null)
			listener.onFailedPlaylistLoad();
	}
	
	private void trackChange(Track newTrack){
		if(listener != null)
			listener.onTrackChange(newTrack);
	}
	
	public void setPlaylist(File M3UFile){
		String fileContent = null;
		try {
			fileContent = getFileContent(M3UFile, "ISO-8859-2");
		} catch (IOException e) {
			failedLoad();
			return;
		}
		
		playlist = M3UParser.parse(fileContent);
		currTrack = 0;
		
		updateStatusAfterLoad();
	}
	
	public void setPlaylist(URL M3UFile){
		//TODO: Implement
	}
	
	public void setPlaylist(String[] trackPaths){
		playlist = new ArrayList<Track>();
		
		for (String path : trackPaths) {
			playlist.add(new Track(null, path));
		}
		
		currTrack = 0;
		
		updateStatusAfterLoad();
	}
	
	private void updateStatusAfterLoad(){
		if(playlist != null){
			if(playlist.size() > 0){
				successfulLoad();
				trackChange(playlist.get(currTrack));
			}
			else{
				failedLoad();
			}
		}
		else {
			failedLoad();
		}
	}
	
	private String getFileContent(File file, String encoding) throws IOException{
		BufferedReader reader = null;
		try{
			reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding));
			StringBuilder sb = new StringBuilder();
			char[] buffer = new char[8192];
			int read;
			while((read = reader.read(buffer, 0, buffer.length)) > 0){
				sb.append(buffer, 0, read);
			}
			
			return sb.toString();
		}
		finally{
			if(reader != null)
				reader.close();
		}		
	}
}
